package com.spc.boot.common.util;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;

public class JsonUtil {
	
	public static ObjectMapper objectMapper;
	
	public static String serialize(Object o) {
		if (o == null)
			return null;
		try {
			return objectMapper.writeValueAsString(o);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public static String serializeNeverNull(Object o){
		String ret = serialize(o);
		if(ret == null)
			return "{}";
		return ret;
	}

	@SuppressWarnings("unchecked")
	public static <T> T deserialize(String json, Class<?> clazz) {
		ObjectMapper mapper = new ObjectMapper();
		T obj;
		try {
			obj = (T) mapper.readValue(json, clazz);
			return obj;
		} catch (JsonParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
}
